import {
  PlusOutlined,
  DeleteOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
} from '@ant-design/icons';
import { Button, Popconfirm, message } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { addMenu, updateMenu, removeMenu } from '@/services/system/menu';
import type { MenuItem, MenuParams } from '@/services/system/types';
import {
  ProFormText,
  ProFormTextArea,
  ProFormDigit,
  ProFormSelect,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import EditForm from '@/components/EditForm';
import { treeMenu } from '@/services/system/menu';
import { getDictValues } from '@/services/system/dictValue';
import { MenuColumns } from './columns';
import SzhomeTable from '@/components/Custom/SzhomeTable';
/**
 * 添加菜单
 *
 * @param fields
 */
const handleAdd = async (fields: MenuItem) => {
  const hide = message.loading('正在新增菜单');

  try {
    await addMenu({ ...fields });
    hide();
    message.success('菜单添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('菜单添加失败，请重试！');
    return false;
  }
};

/**
 * 更新菜单
 *
 * @param fields
 */
const handleUpdate = async (fields: MenuItem, currentRow?: MenuItem) => {
  const hide = message.loading('正在更新菜单');

  try {
    await updateMenu({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('菜单更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('菜单更新失败，请重试');
    return false;
  }
};

/**
 * 删除菜单
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: MenuItem[]) => {
  const hide = message.loading('正在删除菜单');
  if (!selectedRows) return true;

  try {
    await removeMenu(selectedRows.map((row) => row.id));
    hide();
    message.success('菜单删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('菜单删除失败，请重试');
    return false;
  }
};

const menuTypes = await getDictValues('menu.type');
const visibles = await getDictValues('yes.no');
const statusList = await getDictValues('disable.enable');

const Menu: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<MenuItem>();
  const [selectedRowsState, setSelectedRows] = useState<MenuItem[]>([]);

  /** 国际化配置 */

  const columns: ProColumns<MenuItem>[] = [
    ...MenuColumns,
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      width: 220,
      render: (_, record) => [
        <a
          key={'edit-' + record.id}
          onClick={() => {
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key={'delete-' + record.id}
          title="您确定要删除此菜单吗？"
          onConfirm={async () => {
            await handleRemove([record]);
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="Yes"
          cancelText="No"
        >
          <a key="remove">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <SzhomeTable<MenuItem, MenuParams>
        actionRef={actionRef}
        request={treeMenu}
        columns={columns}
        pagination={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增
          </Button>,

          <Popconfirm
            key={'batch_remove'}
            disabled={selectedRowsState?.length == 0}
            title={'您确定要删除已选' + selectedRowsState?.length + '条数据吗？'}
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button key="batch_remove" danger disabled={selectedRowsState?.length == 0}>
              <DeleteOutlined />
              删除
            </Button>
          </Popconfirm>,

          <Button
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <CloudDownloadOutlined /> 导出
          </Button>,

          <Button
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <CloudUploadOutlined /> 导入
          </Button>,
        ]}
        rowSelection={{
          checkStrictly: false,
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      <EditForm
        visible={createModalVisible}
        name="菜单"
        model={currentRow || { id: undefined }}
        onAdd={handleAdd}
        onUpdate={handleUpdate}
        afterEdit={() => {
          setCurrentRow(undefined);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={handleModalVisible}
      >
        <ProFormText name="id" hidden={true} />

        <ProFormTreeSelect
          label="上级菜单"
          name="parentId"
          request={async () => {
            const res = await treeMenu({});
            return res.data;
          }}
          fieldProps={{
            treeDefaultExpandAll: true,
            treeLine: true,
            treeIcon: true,
            fieldNames: {
              label: 'name',
              value: 'id',
            },
          }}
        />

        <ProFormText label="名称" name="name" colProps={{ span: 12 }} />
        <ProFormText label="编码" name="code" colProps={{ span: 12 }} />
        <ProFormText label="请求路径" name="path" />
        <ProFormText label="权限标识" name="perms" colProps={{ span: 12 }} />
        <ProFormText label="图标" name="icon" colProps={{ span: 12 }} />

        <ProFormSelect
          required
          label="类型"
          name="type"
          valueEnum={menuTypes}
          colProps={{ span: 12 }}
        />

        <ProFormSelect
          required
          label="是否隐藏"
          name="visible"
          valueEnum={visibles}
          colProps={{ span: 12 }}
        />

        <ProFormSelect
          required
          label="状态"
          name="status"
          valueEnum={statusList}
          colProps={{ span: 12 }}
        />

        <ProFormDigit
          label="顺序"
          name="rank"
          min={0}
          initialValue={0}
          fieldProps={{ precision: 0 }}
          colProps={{ span: 12 }}
        />
        <ProFormTextArea label="备注" name="remark" />
      </EditForm>
    </PageContainer>
  );
};

export default Menu;
